package gov.pr.celepar.sentinela.admin.action.restricao;

import gov.pr.celepar.framework.util.Data;
import gov.pr.celepar.sentinela.admin.action.BaseAction;
import gov.pr.celepar.sentinela.admin.dao.RestricaoHorarioDAO;
import gov.pr.celepar.sentinela.admin.dao.factory.DAOFactoryServer;
import gov.pr.celepar.sentinela.admin.form.restricao.RestricaoSistemaForm;
import gov.pr.celepar.sentinela.admin.pojo.RestricaoGeral;
import gov.pr.celepar.sentinela.admin.pojo.RestricaoHora;
import gov.pr.celepar.sentinela.admin.pojo.RestricaoSistema;
import gov.pr.celepar.sentinela.admin.pojo.Sistema;
import gov.pr.celepar.sentinela.util.SentinelaUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Collection;
import java.util.ArrayList;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;

public class RestricaoSistemaAction extends BaseAction {
	private static Log logger = LogFactory.getLog(RestricaoSistemaAction.class);

	private RestricaoHorarioDAO restricaoB = null;

	public String executar(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		RestricaoSistemaForm restricaoSistemaForm = (RestricaoSistemaForm) form;

		DAOFactoryServer daoFactory = DAOFactoryServer.getDAOFactory();
		this.restricaoB = daoFactory.getRestricaoDAO();

		this.listarSistemasAutorizados(request);

		if (request.getParameter("sub") != null
				&& request.getParameter("sub").equals("incluir")) {
			this.comunicacao.autorizaOperacao('A', request, response);
			logger.debug("sub ADD");
			incluirSub(restricaoSistemaForm, request);
			consultar(restricaoSistemaForm, request);
			return "alterar_restringirSistema";

		} else if (request.getParameter("sub") != null
				&& request.getParameter("sub").equals("excluir")) {
			this.comunicacao.autorizaOperacao('A', request, response);
			logger.debug("sub REMOVE");
			excluirSub(restricaoSistemaForm, request);
			consultar(restricaoSistemaForm, request);
			return "alterar_restringirSistema";

		} else if (this.CONF_ALTERAR.equalsIgnoreCase(restricaoSistemaForm
				.getAcao())) {
			this.comunicacao.autorizaOperacao('A', request, response);
			alterar(restricaoSistemaForm, request);
			return "alterar_restringirSistema";

		} else if (this.CONF_INCLUIR.equalsIgnoreCase(restricaoSistemaForm
				.getAcao())) {
			this.comunicacao.autorizaOperacao('I', request, response);
			logger.debug("confirma_inclusao");
			incluir(restricaoSistemaForm, request);
			consultar(restricaoSistemaForm, request);
			return "alterar_restringirSistema";

		} else if (this.CONF_EXCLUIR.equalsIgnoreCase(restricaoSistemaForm
				.getAcao())) {
			this.comunicacao.autorizaOperacao('E', request, response);
			excluir(restricaoSistemaForm, request);
			restricaoSistemaForm.reset(mapping, request);
			return "lista_restringirSistema";

		} else if (this.INCLUIR
				.equalsIgnoreCase(restricaoSistemaForm.getAcao())) {
			this.comunicacao.autorizaOperacao('I', request, response);
			return "incluir_restringirSistema";

		} else if (this.EXCLUIR
				.equalsIgnoreCase(restricaoSistemaForm.getAcao())) {
			this.comunicacao.autorizaOperacao('E', request, response);
			consultar(restricaoSistemaForm, request);
			return "excluir_restringirSistema";

		} else if (this.ALTERAR
				.equalsIgnoreCase(restricaoSistemaForm.getAcao())) {
			this.comunicacao.autorizaOperacao('A', request, response);
			consultar(restricaoSistemaForm, request);
			return "alterar_restringirSistema";
		}
		// Default = consultar
		this.comunicacao.autorizaOperacao('L', request, response);
		consultar(restricaoSistemaForm, request);
		return "consultar_restringirSistema";
	}

	private void incluir(RestricaoSistemaForm form, HttpServletRequest request) {
		RestricaoGeral s = new RestricaoGeral();
		try {
			s.setTipo(RestricaoGeral.RESTRICAO_HORA_SISTEMA);
			Sistema sis = new Sistema();
			sis.setCodSistema(Long.decode(form.getCodSistema()));
			s.setSistema(sis);
			s.setDataInicio(Data.formataData(form.getDataInicio()));
			s.setDataFim(Data.formataData(form.getDataFim()));
		} catch (Exception e) {
			this.addMessageAlert("Informações inválidas", request);
		}
		try {
			this.restricaoB.incluirRestricaoGeral(s);
			// inserido - inserir o código gerado
			form.setCodRestricao(Long.toString(s.getCodRestricao()));
		} catch (Exception e) {
			this.addMessageException(e, request);
		}
	}

	private void excluir(RestricaoSistemaForm form, HttpServletRequest request) {
		RestricaoGeral s = new RestricaoGeral();

		s.setCodRestricao(Long.decode(form.getCodRestricao()));

		try {
			this.restricaoB.excluir(s);
		} catch (Exception e) {
			this.addMessageException(e, request);
		}
	}

	private void incluirSub(RestricaoSistemaForm form,
			HttpServletRequest request) throws Exception {
		logger.debug("incluirSub");
		RestricaoGeral rg = new RestricaoGeral();
		rg.setCodRestricao(Long.decode(form.getCodRestricao()));
		rg.setTipo(RestricaoGeral.RESTRICAO_HORA_SISTEMA);

		Collection<RestricaoHora> c = new ArrayList<RestricaoHora>();
		String horaInicio = form.getHoraInicio();
		String horaFim = form.getHoraFim();
		RestricaoHora rh = new RestricaoSistema();
		rh.setHoraInicio(SentinelaUtil.getMinutosFromHora(horaInicio));
		rh.setHoraFim(SentinelaUtil.getMinutosFromHora(horaFim));
		rh.setDiaNormal(form.getDiaSemanaNormal());
		rh.setSabado(form.getDiaSemanaSabado());
		rh.setDomingo(form.getDiaSemanaDomingo());
		c.add(rh);
		rg.setHoras(c);

		try {
			this.restricaoB.incluirRestricaoSistema(rg);
		} catch (Exception e) {
			this.addMessageException(e, request);
		}
	}

	private void excluirSub(RestricaoSistemaForm form,
			HttpServletRequest request) throws Exception {
		logger.debug("excluirSub");
		RestricaoGeral rg = new RestricaoGeral();
		rg.setCodRestricao(Long.decode(form.getCodRestricao()));
		rg.setTipo(RestricaoGeral.RESTRICAO_HORA_SISTEMA);

		int rest[] = form.getRestricoesHoras();
		if (rest == null)
			return;

		Collection<RestricaoHora> c = new ArrayList<RestricaoHora>();
		for (int i = 0; i < rest.length; i++) {
			RestricaoHora rh = new RestricaoSistema();
			rh.setCodRestricaoHora(Long.valueOf(rest[i]));
			c.add(rh);
		}
		rg.setHoras(c);
		try {
			this.restricaoB.excluirRestricaoSistema(rg);
		} catch (Exception e) {
			this.addMessageException(e, request);
		}
	}

	private void alterar(RestricaoSistemaForm form, HttpServletRequest request)
			throws Exception {

		RestricaoGeral sNew = new RestricaoGeral();
		sNew.setCodRestricao(Long.decode(form.getCodRestricao()));
		sNew.setTipo(RestricaoGeral.RESTRICAO_HORA_SISTEMA);
		Sistema sis = new Sistema();
		sis.setCodSistema(Long.decode(form.getCodSistema()));
		sNew.setSistema(sis);
		sNew.setDataInicio(Data.formataData(form.getDataInicio()));
		sNew.setDataFim(Data.formataData(form.getDataFim()));
		sNew.setAtivo(form.isAtivo());

		try {
			this.restricaoB.alterarRestricaoSistema(sNew);
		} catch (Exception e) {
			this.addMessageException(e, request);
		}
	}

	private void consultar(RestricaoSistemaForm form, HttpServletRequest request)
			throws Exception {
		RestricaoGeral rg = null;
		try {
			rg = this.restricaoB.consultarRestricaoSistema(Long.decode(form
					.getCodRestricao()));

			form.setCodSistema(Long.toString(rg.getSistema().getCodSistema()));
			form.setDataInicio(Data.formataData(rg.getDataInicio()));
			form.setDataFim(Data.formataData(rg.getDataFim()));
			form.setAtivo(rg.getAtivo());

			form.setHoraInicio("");
			form.setHoraFim("");
			form.setDiaSemanaDomingo(false);
			form.setDiaSemanaSabado(false);
			form.setDiaSemanaNormal(false);

			Collection c = rg.getHoras();
			request.setAttribute("listaRestricoes", c);
		} catch (Exception e) {
			this.addMessageException(e, request);
		}
	}
}
